package com.caesi.tacacaesifinal.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;

public class Serializador {

    /**
     * este método tranforma um objeto para um array de bytes
     * 
     * @param o
     *            Objeto a ser tranformado
     * @return Array de bytes que representa o objeto
     */
    public static byte[] serializeObject(Object o) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ObjectOutput out = new ObjectOutputStream(bos);
            out.writeObject(o);
            out.close();

            // Get the bytes of the serialized object
            byte[] buf = bos.toByteArray();

            return buf;
        } catch (IOException ioe) {
            Log.e("serializeObject", "error", ioe);

            return null;
        }
    }

    /**
     * Este método tranforma um array de bytes em um objeto
     * 
     * @param b
     *            O array de bytes a ser tranformado
     * @return Um objeto
     */
    public static Object deserializeObject(byte[] b) {
        try {
            ObjectInputStream in = new ObjectInputStream(
                    new ByteArrayInputStream(b));
            Object object = in.readObject();
            in.close();

            return object;

        } catch (ClassNotFoundException cnfe) {
            cnfe.printStackTrace();

            return null;
        } catch (IOException ioe) {
            ioe.printStackTrace();
            return null;
        }

    }

    public static Object toObject(byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = ois.readObject();
        } catch (IOException ex) {
            // TODO: Handle the exception
        } catch (ClassNotFoundException ex) {
            // TODO: Handle the exception
        }

        return obj;
    }

    public static byte[] toByteArray(Bitmap myBitmap) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        myBitmap.compress(CompressFormat.PNG, 0, outputStream);

        return outputStream.toByteArray();
    }

}
